package com.hjc.controller;

import com.google.code.kaptcha.Producer;
import com.hjc.entity.*;
import com.hjc.service.AuthService;
import com.hjc.service.UserService;
import com.hjc.utils.DigestUtil;
import com.hjc.utils.TokenUtils;
import com.hjc.utils.WarehouseConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
public class LoginController {
    //注入DefaultCaptcha的bean对象
    @Resource(name = "captchaProducer")
    private Producer producer;

    //注入redis模板
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UserService userService;

    @Autowired
    private TokenUtils tokenUtils;

    @Autowired
    private AuthService authService;

    @RequestMapping("/captcha/captchaImage")
    public void captchaImage(HttpServletResponse response) {
    //    生成验证码图片的文件
        String text = producer.createText();
    //    使用验证码文本生成验证码图片
        BufferedImage image = producer.createImage(text);
    //    将验证码文本作为键保存到redis，设置键的过期时间为5分钟
        redisTemplate.opsForValue().set(text,"",60*5, TimeUnit.SECONDS);

    //   将验证码图片响应给前端
    //    设置响应正文image/jpeg
        response.setContentType("image/jpeg");
    //    将验证码图片写给前端
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            //使用响应对象的字节输出流写入验证码图片
            ImageIO.write(image,"jpg",out);
        //    刷新
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 登录请求
     * @param loginUser
     * @return
     */
    @RequestMapping("/login")
    public Result login(@RequestBody LoginUser loginUser) {
        String verificationCode = loginUser.getVerificationCode();
        //拿用户输入的密码进行md5加密后与数据库的密码进行比较
        String userPwd = DigestUtil.hmacSign(loginUser.getUserPwd());
        if (!redisTemplate.hasKey(verificationCode)) {
            return Result.err(Result.CODE_ERR_BUSINESS,"验证码错误！");
        }
        User user = userService.queryUserByCode(loginUser.getUserCode());
        if(user == null) {
            return Result.err(Result.CODE_ERR_BUSINESS,"用户名不存在！");
        } else if(user.getUserState().equals(WarehouseConstants.USER_STATE_NOT_PASS)) {
            return Result.err(Result.CODE_ERR_BUSINESS,"用户未审核！");
        }else if(!user.getUserPwd().equals(userPwd)) {
            return Result.err(Result.CODE_ERR_BUSINESS,"密码错误！");
        }else {
            CurrentUser currentUser = new CurrentUser(user.getUserId(),user.getUserCode(),user.getUserName());
            //生成token并保存到redis
            String token = tokenUtils.loginSign(currentUser,userPwd);
            return Result.ok("登录成功！",token);
        }
    }

    /**
     * 获取当前登录对象并返回给前端
     * @param token
     * @return
     */
    @RequestMapping("/curr-user")
    public Result currentUser(@RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String token) {
        CurrentUser currentUser = tokenUtils.getCurrentUser(token);
        return Result.ok(currentUser);
    }

    /**
     * 加载当前用户权限树
     * @param token
     * @return
     */
    @RequestMapping("/user/auth-list")
    public Result loadAuthTree(@RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String token) {
        CurrentUser currentUser = tokenUtils.getCurrentUser(token);
        List<Auth> authTree = authService.findAuthTreeByUserId(currentUser.getUserId());
        return Result.ok(authTree);
    }

    /**
     * 退出登录
     * @param token
     * @return
     */
    @RequestMapping("/logout")
    public Result logout(@RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String token) {
        redisTemplate.delete(token);
        return Result.ok("您已退出登录啦！！！");
    }






}
